//
//  ViewController.m
//  ThinkingPictures
//
//  Created by Anyeler on 16/2/19.
//  Copyright © 2016年 Anyeler. All rights reserved.
//

#import "ViewController.h"
#import "CZGuessModel.h"

//定义答案区按钮宽度
#define kButtonWidth 30

//定义答案区按钮间隔
#define kMargin 10

//屏幕宽度
#define kScreenSize [UIScreen mainScreen].bounds.size

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *imageButton;
@property (weak, nonatomic) IBOutlet UILabel *indexLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) IBOutlet UIButton *coinButton;
@property (weak, nonatomic) IBOutlet UIView *answerView;
@property (weak, nonatomic) IBOutlet UIView *optionsView;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) UIView *coverView;

@property (assign,nonatomic) NSInteger index;
@property (strong,nonatomic) NSArray *dataArray;

@end

@implementation ViewController

#pragma mark -
#pragma mark - 懒加载数据
-(NSArray *)dataArray {
    if (nil == _dataArray) {
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil];
        
        NSArray *tempArray = [NSArray arrayWithContentsOfFile:path];
        
        NSMutableArray *mutableArray = [NSMutableArray array];
        
        for (NSDictionary *dict in tempArray) {
            CZGuessModel *guessModel = [CZGuessModel guessModelWithDict:dict];
            [mutableArray addObject:guessModel];
        }
        
        _dataArray = mutableArray;
    }
    
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.index = 0;
    [self setupUI];
    
}

#pragma mark -
#pragma mark - 初始化UI界面
- (void)setupUI {
    //取出数据
    CZGuessModel *guessMode = self.dataArray[self.index];
    
    //设置索引
    self.indexLabel.text = [NSString stringWithFormat:@"%ld/%lu",(long)self.index + 1,self.dataArray.count];
    
    //设置提示
    self.tipLabel.text = guessMode.title;
    
    
    //设置图片
    [self.imageButton setImage:[UIImage imageNamed:guessMode.icon] forState:UIControlStateNormal];
    
    /**
     初始化answerView
     */
    [self setupAnswerViewWithLength:guessMode.answer.length];
    
    /**
     初始化optionsView
     */
    [self setupOptionsViewWithOptions:guessMode.options];
    
    [self initCoverView];
}

- (void)initCoverView {
    
    UIView *coverView = [[UIView alloc] initWithFrame:self.view.bounds];
    
    [coverView setBackgroundColor:[UIColor blackColor]];
    
    coverView.alpha = 0;
    
    self.coverView = coverView;
    
    [self.view addSubview:coverView];
}

#pragma mark - 初始化answerView
- (void)setupAnswerViewWithLength:(NSInteger)length {
    
    /**
     1. 答案区的个数不同 由答案的长度决定
     */
    
    //确定个数
    NSInteger count = length;
    
    CGFloat startX = (kScreenSize.width - count * kButtonWidth - (count - 1) * kMargin) / 2;
    
    [self.answerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    for (int i = 0; i < count; i++) {
        
        CGFloat kButtonX = startX + i * (kButtonWidth + kMargin);
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(kButtonX, 0, kButtonWidth, kButtonWidth)];
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer_highlighted"] forState:UIControlStateHighlighted];
        
        [btn addTarget:self action:@selector(didClickAnswer:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.answerView addSubview:btn];
    }
    
}



#pragma mark -
#pragma mark - 答案区绑定事件
- (void)didClickAnswer:(UIButton *)sender {
    /**
      1.清除按钮的文本对应文本
      2.设置文本颜色为黑色
      3.设置option区对应的按钮显示
      4.设置option区可以用户交互
    */
    if (sender.currentTitle.length == 0) {
        return;
    }
    
    NSString *str = sender.currentTitle;
    
    [sender setTitle:@"" forState:UIControlStateNormal];
    
    [self.optionsView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = obj;
        
        if ([str isEqualToString:btn.currentTitle]) {
            btn.hidden = NO;
            *stop = YES;
        }
        
    }];
    
    [self.answerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = obj;
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }];
    
    
    
    
    
    
    self.optionsView.userInteractionEnabled = YES;
}


#pragma mark - 初始化optionsView
- (void)setupOptionsViewWithOptions:(NSArray *)options {
    /**
     1. 选项一定 都是 21 个按钮
     2. 行列规定 3 行 7 列
     */
    
    //列数
    int column = 7;
    
    //按钮数
    int count = 21;
    
    //中间间隔距离
    CGFloat margin = (kScreenSize.width - column * kButtonWidth) / (column + 1);
    
    for (int i = 0; i < count; i++) {
        if (_optionsView.subviews.count != count) {
            NSInteger columnindex = i % column;
            NSInteger rowindex = i / column;
            
            CGFloat buttonX = (columnindex + 1) * margin + columnindex * kButtonWidth;
            CGFloat buttonY = (rowindex + 1) * margin + rowindex * kButtonWidth;
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(buttonX, buttonY, kButtonWidth, kButtonWidth)];
            
            [btn setTitle:options[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_option"] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_option_highlighted"] forState:UIControlStateHighlighted];
            [btn addTarget:self action:@selector(didClickOptions:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.optionsView addSubview:btn];
        }
        else {
            UIButton *btn = (UIButton *)_optionsView.subviews[i];
            [btn setTitle:options[i] forState:UIControlStateNormal];
            btn.hidden = NO;
        }
    }
    
    
}


#pragma mark -
#pragma mark - Options按钮事件
- (void)didClickOptions:(UIButton *)sender {
    
    /**
     1 、 取出button的文本
     2、  隐藏按钮
     3、  把Button文本设置到答案区中
     */
    
    NSString * title = sender.currentTitle;
    
    sender.hidden = YES;
    
    [self.answerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = obj;
        
        if (btn.currentTitle.length == 0) {
            [btn setTitle:title forState:UIControlStateNormal];
            *stop = YES;
        }
    }];
    
    __block BOOL isComplete = YES;
    
    [self.answerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = obj;
        
        if (btn.currentTitle.length == 0) {
            isComplete = NO;
            *stop = YES;
        }
        
    }];
   
    if (isComplete) {
        self.optionsView.userInteractionEnabled = NO;
        
        /**
         1. 取出用户答案
         2.与正确答案作对比
         3.判断答案是否正确
         */
        
        NSMutableString *userAnswer = [[NSMutableString alloc] init];
        
        [self.answerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *btn = obj;
            
            [userAnswer appendString:btn.currentTitle];
        }];
        
        CZGuessModel *guessModel = self.dataArray[self.index];
        
        NSString *rigthAnswer = guessModel.answer;
        
        NSInteger coin = self.coinButton.currentTitle.integerValue;
        
        if ([rigthAnswer isEqualToString:userAnswer]) {
            
            
            //答案正确
            
            [self performSelector:@selector(nextButtoning:) withObject:nil afterDelay:1];
            
            coin += 100;
        
        }else {
            
            //答案错误
            [self.answerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIButton *btn = obj;
                [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            }];
            
            coin -= 1000;
        }
        
        NSString *str = [NSString stringWithFormat:@"%lu",coin];
        
        [self.coinButton setTitle:str forState:UIControlStateNormal];
    
        
    }
    
    
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -
#pragma mark - 提示
- (IBAction)tipButton:(UIButton *)sender {
    /**
     1. 减去1000金币
     2. 取出正确答案的第一个字
     3. 在答案区域的第一个button上显示 第一个字, 其他按钮文本清空
     4. 选项区域中, 只有第一字对应的button隐藏, 其他的显示出来
     5. 答案区域的文本要变为黑色
     6. 允许选项区域用户交互
     7. 对用户的金币数量做判断, 如果不够减就提示用户
     */
    
    NSInteger coin = self.coinButton.currentTitle.integerValue;
    
    if (coin < 1000) {
        
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"逗比没钱了" preferredStyle:UIAlertControllerStyleAlert];
   
        UIAlertAction *sureActiion = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alter addAction:sureActiion];
        [alter addAction:cancelAction];
 
        [self presentViewController:alter animated:YES completion:nil];
        return;
    }
    
    coin -= 1000;
  
    NSString *coinString = [NSString stringWithFormat:@"%ld",coin];
    [self.coinButton setTitle:coinString forState:UIControlStateNormal];
    
    CZGuessModel *guessModel = self.dataArray[self.index];
    
    NSString *tempstr = guessModel.answer;
    
    NSString * str = [tempstr substringToIndex:1];
    
    [self.answerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn =obj;
        
        if (idx == 0) {
            [btn setTitle:str forState:UIControlStateNormal];
        }else {
            [btn setTitle:@"" forState:UIControlStateNormal];
        }
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }];
    
    [self.optionsView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = obj;
        
        if ([str isEqualToString:btn.currentTitle]) {
            btn.hidden = YES;
        }else {
            btn.hidden = NO;
        }
    }];
    
    self.optionsView.userInteractionEnabled = YES;
    
}

#pragma mark -
#pragma mark - 点击大图事件
- (IBAction)bigimage:(UIButton *)sender {
    
    if (self.coverView.alpha == 0) {
        
        [self changeSize:nil];
     
    }else {
      
        [UIView animateWithDuration:0.5 animations:^{
            self.coverView.alpha = 0;
            self.imageButton.transform = CGAffineTransformIdentity;
        }];
        
    }
  
}

#pragma mark -
#pragma mark - 放大
- (IBAction)changeSize:(UIButton *)sender {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.coverView.alpha = 0.6;
        self.imageButton.transform = CGAffineTransformMakeScale(1.5, 1.5);
    }];
    
    [self.view bringSubviewToFront:self.imageButton];
}

#pragma mark -
#pragma mark - 下一题按钮事件
- (IBAction)nextButtoning:(UIButton *)sender {
    
    if (self.index + 1 == self.dataArray.count) {
        
        return;
    }
    
    self.index++;
    [self setupUI];
    
    self.nextButton.enabled = (self.index + 1 != self.dataArray.count);
    self.optionsView.userInteractionEnabled = YES;
}

#pragma mark -
#pragma mark - 修改状态栏样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - 是否隐藏状态栏
-(BOOL)prefersStatusBarHidden {
    return YES;
}

@end
